import React, { Component } from 'react'
import Miracle from 'incu-webview'
import Input from './Input'
import apis from '../apis'
import { Toast, Modal } from 'antd-mobile'
import styles from './index.module.css'

class Index extends Component {
  constructor(props) {
    super(props)
    this.state = {
      username: '',
      password: '',
      isApp: true,
    }
  }

  componentDidMount() {
    if(Miracle.isApp()) {
      this.setState({ isApp: true })
      if(!window.appReady) {
        Toast.loading('加载中...', 0)
        Miracle.onAppReady(() => {
          Toast.hide();
        })
      }
    } else {
      this.setState({ isApp: false })
    }
    
  }

  handleChange(event) {
    const target = event.target
    this.state[target.name] !== undefined && this.setState({
      [target.name]: target.value
    })
  }

  login() {
    Toast.loading('登录中...')
    apis.login(this.state.username, this.state.password).then(token => {
      console.log(token)
      this.props.history.push('/result', { token })
    }).catch(err => {
      console.log(err)
      Toast.hide()
      Toast.fail(err.msg)
    })
  }
  
  loginByMiracle() {
    const data = Miracle.getData()
    console.log(data.user.token)
      this.props.history.push('/result', { token: data.user.token })
  }

  render() {
    return (
      <div className={styles['page-index']}>
      <Modal
        visible={this.state.isApp}
        transparent
        maskClosable={false}
        title="提示"
        footer={[{ text: '去下载', onPress: () => { window.location.href = "http://incu.ncuos.com/" } }]}
      >
        <div style={{ height: 240, overflow: 'scroll' }}>
          <p><img src="http://incu.ncuos.com/images/logo.png" style={{width:'92px', border: '1px solid #eee', borderRadius:'20px'}} /></p>
          请在 <strong style={{color: '#4fb2ff'}}>南大家园APP</strong> 内<br/>
          进入“校园生活”打开本应用<br/>
如果暂未安装<br/>
戳下面按键直达下载页面喔
        </div>
      </Modal>
        {this.state.isApp ? 
        <div className={styles['login-box']}>
          <div>
            <button onClick={this.loginByMiracle.bind(this)} className={styles['btn']}>
              <img alt="" src={require('../resources/incu-login.svg')}/>
            </button>
          </div>
        </div> : 
        <div className={styles['login-box']}>
          <div className={styles['form-group']}>
            <Input type="number" name="username" onChange={this.handleChange.bind(this)} placeholder="用户名（学号）"/>
          </div>
          <div className={styles['form-group']}>
            <Input type="password" name="password" onChange={this.handleChange.bind(this)} placeholder="云家园密码" />
          </div>
          <div>
            <button onClick={this.login.bind(this)} className={styles['btn']}>
              <img alt="" src={require('../resources/index-login.svg')} />
            </button>
          </div>
        </div>}
      </div>
    )
  }
}

export default Index